package com.atguigu.gulimall.search.service;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.BulkRequest;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import co.elastic.clients.elasticsearch.core.IndexResponse;
import co.elastic.clients.elasticsearch.core.bulk.BulkResponseItem;
import com.atguigu.gulimall.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.constant.EsConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author majinhui
 * @description
 * @create 2024/7/31 10:34
 **/
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService{

    @Autowired
    private ElasticsearchClient esClient;

    @Override
    public void productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        BulkRequest.Builder br = new BulkRequest.Builder();

         for (SkuEsModel model : skuEsModels) {
            br.operations(op -> op
                    .index(idx -> idx
                            .index("products")
                            .id(model.getSkuId().toString())
                            .document(model)
                    )
            );
        }

        BulkResponse result = esClient.bulk(br.build());
        // Log errors, if any
        if (result.errors()) {
            log.error("Bulk had errors");
            for (BulkResponseItem item: result.items()) {
                if (item.error() != null) {
                    log.error(item.error().reason());
                }
            }
        }
        log.info("商品上架成功：{}",result.took());
    }
}
